// 声破天主页JavaScript

document.addEventListener('DOMContentLoaded', function() {
    // 初始化多语言支持
    if (window.i18n) {
        window.i18n.initLanguage();
    } else {
        console.error('国际化模块未加载！');
    }
    
    // 初始化卡片悬停效果
    initCardHoverEffects();
    
    // 初始化导航按钮
    initNavigationButtons();
    
    // 初始化语言选择按钮
    initLanguageButtons();
    
    // 初始化滚动检测
    initScrollDetection();
    
    // 加载用户数据并更新界面
    loadUserDataAndUpdateUI();
    
    // 调用初始化功能
    initDropdowns();
    updateUserInfo();
    
    // 应用样式调整
    applyStyles();
    
    // 显示用户信息或登录/注册按钮
    updateUserUI();
    
    // 初始化语言切换
    initLanguageSelector();
    
    // 初始化顶部栏滚动隐藏
    initTopBarScrollHandling();

    initTheme();
    initUserDropdown();
    initPlayer();

    // 登录状态处理
    checkLoginStatus();
    
    // 更新用户信息
    updateUserInfo();

    // 创建全局音频播放器实例（如果不存在）
    if (!window.globalAudioPlayer) {
        window.globalAudioPlayer = new Audio();
        window.globalAudioPlayer.volume = 0.7; // 默认音量70%
        
        // 恢复之前的音频状态（如果有）
        const savedAudioState = localStorage.getItem('audioPlaybackState');
        if (savedAudioState) {
            try {
                const state = JSON.parse(savedAudioState);
                if (state.src) {
                    window.globalAudioPlayer.src = state.src;
                    window.globalAudioPlayer.currentTime = state.currentTime || 0;
                    if (state.isPlaying) {
                        window.globalAudioPlayer.play().catch(e => {
                            console.log("自动播放失败，需要用户交互:", e);
                        });
                    }
                }
            } catch (e) {
                console.error("恢复音频状态失败:", e);
            }
        }
        
        // 监听页面关闭，保存音频状态
        window.addEventListener('beforeunload', saveAudioState);
    }

    // 初始化公共功能
    initCommonFeatures();
});

// 加载用户数据并更新界面
function loadUserDataAndUpdateUI() {
    // 尝试从localStorage获取当前用户
    const currentUserJson = localStorage.getItem('shengpotian_current_user');
    
    // 获取顶部栏上的认证按钮区域
    const authButtonsContainers = document.querySelectorAll('.auth-buttons');
    
    if (currentUserJson) {
        try {
            // 解析用户数据
            const currentUser = JSON.parse(currentUserJson);
            
            // 更新界面显示已登录状态
            authButtonsContainers.forEach(container => {
                // 清空容器
                container.innerHTML = '';
                
                // 创建用户头像和菜单
                const userMenu = document.createElement('div');
                userMenu.className = 'user-profile-menu';
                
                // 添加头像和用户名
                userMenu.innerHTML = `
                    <div class="user-avatar">
                        <img src="${currentUser.avatar}" alt="${currentUser.username}">
                    </div>
                    <span class="username">${currentUser.username}</span>
                    <i class="fas fa-chevron-down"></i>
                    <div class="user-dropdown">
                        <div class="dropdown-account">
                            <i class="fas fa-user"></i> ${currentUser.username}
                        </div>
                        <a href="profile.html" class="dropdown-item"><i class="fas fa-id-card"></i> 个人资料</a>
                        <a href="premium.html" class="dropdown-item"><i class="fas fa-gem"></i> 升级Premium</a>
                        <a href="history.html" class="dropdown-item"><i class="fas fa-history"></i> 历史记录</a>
                        <div class="dropdown-divider"></div>
                        <a href="about.html" class="dropdown-item"><i class="fas fa-question-circle"></i> 关于</a>
                        <a href="download.html" class="dropdown-item"><i class="fas fa-download"></i> 下载</a>
                        <a href="settings.html" class="dropdown-item"><i class="fas fa-cog"></i> 设置</a>
                        <div class="dropdown-divider"></div>
                        <a href="#" class="dropdown-item logout-btn"><i class="fas fa-sign-out-alt"></i> 退出</a>
                    </div>
                `;
                
                // 添加到容器
                container.appendChild(userMenu);
                
                // 添加用户菜单交互
                initUserMenuInteractions(userMenu);
            });
            
            console.log('已加载用户数据:', currentUser.username);
        } catch (error) {
            console.error('解析用户数据出错:', error);
            // 发生错误时移除损坏的数据
            localStorage.removeItem('shengpotian_current_user');
        }
    } else {
        console.log('未登录状态');
        // 确保显示登录/注册按钮
        authButtonsContainers.forEach(container => {
            if (container.querySelector('.login-btn')) {
                // 按钮已存在，不需要更改
                return;
            }
            
            // 重置为未登录状态的按钮
            container.innerHTML = `
                <a href="login.html" class="login-btn"><i class="fas fa-sign-in-alt"></i> <span data-i18n="login">登录</span></a>
                <a href="register.html" class="register-btn"><i class="fas fa-user-plus"></i> <span data-i18n="register">注册</span></a>
            `;
            
            // 更新i18n标签
            if (window.i18n) {
                window.i18n.updatePageLanguage();
            }
        });
    }
}

// 初始化用户菜单交互
function initUserMenuInteractions(userMenu) {
    if (!userMenu) return;
    
    // 点击头像显示/隐藏下拉菜单
    userMenu.addEventListener('click', function(e) {
        const dropdown = this.querySelector('.user-dropdown');
        if (dropdown) {
            dropdown.classList.toggle('active');
            e.stopPropagation();
        }
    });
    
    // 点击登出按钮
    const logoutBtn = userMenu.querySelector('.logout-btn');
    if (logoutBtn) {
        logoutBtn.addEventListener('click', function(e) {
            e.preventDefault();
            e.stopPropagation();
            
            // 清除所有用户数据
            localStorage.removeItem('shengpotian_current_user');
            localStorage.removeItem('currentUser');
            
            // 重定向到首页，而不是仅刷新当前页面
            window.location.href = 'index.html';
        });
    }
    
    // 点击页面其他位置关闭下拉菜单
    document.addEventListener('click', function() {
        const dropdown = userMenu.querySelector('.user-dropdown');
        if (dropdown && dropdown.classList.contains('active')) {
            dropdown.classList.remove('active');
        }
    });
}

// 初始化滚动检测
function initScrollDetection() {
    // 处理主内容区域的滚动
    initScrollForElement('.content');
    
    // 处理播放器内容区域的滚动
    initScrollForElement('.player-content');
}

// 为特定元素初始化滚动检测
function initScrollForElement(selector) {
    const container = document.querySelector(selector);
    const topBar = container ? container.closest('.content') ? 
        document.querySelector('.content > .top-bar') : 
        document.querySelector('.player-content-container > .top-bar') : null;
        
    if (!container || !topBar) return;
    
    let lastScrollTop = 0;
    const scrollThreshold = 50; // 滚动阈值，避免微小滚动触发
    
    // 监听滚动事件
    container.addEventListener('scroll', function() {
        const scrollTop = this.scrollTop;
        
        // 如果滚动了一定距离，才触发行为
        if (Math.abs(scrollTop - lastScrollTop) > scrollThreshold) {
            // 向上滚动 - 显示导航栏
            if (scrollTop < lastScrollTop) {
                topBar.classList.add('visible');
            } 
            // 向下滚动 - 隐藏导航栏
            else {
                topBar.classList.remove('visible');
            }
            
            lastScrollTop = scrollTop;
        }
        
        // 当回到顶部时，总是显示导航栏
        if (scrollTop === 0) {
            topBar.classList.add('visible');
        }
    });
    
    // 初始状态，如果在顶部则显示导航栏
    if (container.scrollTop === 0) {
        topBar.classList.add('visible');
    }
}

// 初始化语言选择按钮
function initLanguageButtons() {
    const languageButtons = document.querySelectorAll('.language-btn');
    
    // 根据当前语言设置激活状态
    updateActiveLanguageButton();
    
    // 为每个语言按钮添加点击事件
    languageButtons.forEach(button => {
        button.addEventListener('click', function() {
            const langCode = this.getAttribute('data-lang');
            if (langCode && window.i18n) {
                window.i18n.setLanguage(langCode);
                updateActiveLanguageButton();
                
                // 更新页面文本
                window.i18n.updatePageLanguage();
            }
        });
    });
}

// 更新激活的语言按钮
function updateActiveLanguageButton() {
    if (!window.i18n) return;
    
    const currentLang = window.i18n.getCurrentLanguage();
    const languageButtons = document.querySelectorAll('.language-btn');
    
    languageButtons.forEach(button => {
        const buttonLang = button.getAttribute('data-lang');
        if (buttonLang === currentLang) {
            button.classList.add('active');
        } else {
            button.classList.remove('active');
        }
    });
}

// 初始化卡片悬停效果
function initCardHoverEffects() {
    const cards = document.querySelectorAll('.card, .artist-card');
    
    cards.forEach(card => {
        const playButton = card.querySelector('.play-button');
        
        if (playButton) {
            // 播放按钮点击
            playButton.addEventListener('click', function(e) {
                e.stopPropagation(); // 阻止冒泡，避免触发卡片点击
                
                const cardTitle = card.querySelector('h3').textContent;
                const cardType = card.querySelector('p').textContent;
                const cardImage = card.querySelector('img').src;
                
                console.log(`开始播放: ${cardTitle} (${cardType})`);
                
                // 更新底部播放器信息
                updateNowPlaying(cardTitle, cardType, cardImage);
                
                // 使用外部播放器模块的函数更新播放按钮
                if (typeof updatePlayButton === 'function') {
                    updatePlayButton(true);
                }
                
                // 跳转到播放器页面
                navigateToPlayer(cardTitle, cardType, cardImage);
            });
        }
        
        // 卡片点击
        card.addEventListener('click', function() {
            const cardTitle = this.querySelector('h3').textContent;
            const cardType = this.querySelector('p').textContent;
            const cardImage = this.querySelector('img').src;
            
            console.log(`打开详情页: ${cardTitle} (${cardType})`);
            
            // 跳转到播放器页面
            navigateToPlayer(cardTitle, cardType, cardImage);
        });
    });
    
    // 初始化播放列表项点击事件
    initPlaylistItemsClick();
}

// 初始化播放列表项点击事件
function initPlaylistItemsClick() {
    const playlistItems = document.querySelectorAll('.playlist-item');
    
    playlistItems.forEach(item => {
        item.addEventListener('click', function() {
            const playlistTitle = this.querySelector('h3').textContent;
            const playlistType = this.querySelector('p').textContent;
            
            console.log(`打开播放列表: ${playlistTitle}`);
        });
    });
    
    // 初始化曲目列表点击事件（如果有）
    const trackItems = document.querySelectorAll('.track-item');
    
    trackItems.forEach(item => {
        item.addEventListener('click', function() {
            if(!this.querySelector('.track-name')) return;
            
            const trackName = this.querySelector('.track-name').textContent;
            const trackArtist = document.querySelector('.track-artist') ? 
                document.querySelector('.track-artist').textContent : "周杰伦";
            
            console.log(`播放曲目: ${trackName}`);
        });
    });
}

// 导航到播放器页面
function navigateToPlayer(title, type, imageSrc) {
    // 提取类型（播放列表、歌曲、艺术家等）
    let itemType = 'track';
    let artist = '周杰伦'; // 默认艺术家
    
    if (type.includes('播放列表')) {
        itemType = 'playlist';
    } else if (type.includes('艺术家')) {
        itemType = 'artist';
        artist = title; // 如果是艺术家，则艺术家名就是标题
    }
    
    // 构建URL参数
    const params = new URLSearchParams();
    params.append('name', title);
    params.append('type', itemType);
    params.append('artist', artist);
    
    // 如果有图片地址，也添加到参数中
    if (imageSrc) {
        // 从完整URL中提取相对路径
        const imagePath = imageSrc.split('/').slice(-2).join('/'); // 假设格式是 "assets/images/covers/cover2.jpg"
        params.append('image', imagePath);
    }
}

// 初始化导航按钮
function initNavigationButtons() {
    const backBtn = document.querySelector('.navigation-buttons .nav-btn:first-child');
    const forwardBtn = document.querySelector('.navigation-buttons .nav-btn:last-child');
    
    if (backBtn) {
        backBtn.addEventListener('click', function() {
            console.log('返回上一页');
            window.history.back();
        });
    }
    
    if (forwardBtn) {
        forwardBtn.addEventListener('click', function() {
            console.log('前进到下一页');
            window.history.forward();
        });
    }
}

// 更新"当前播放"区域信息
function updateNowPlaying(trackName, artistName, imageSrc) {
    const trackNameElement = document.querySelector('.track-name');
    const artistNameElement = document.querySelector('.artist-name');
    const trackImageElement = document.querySelector('.track-image img');
    
    if (trackNameElement) {
        trackNameElement.textContent = trackName;
        trackNameElement.removeAttribute('data-i18n'); // 移除国际化标记，使用实际歌曲名
    }
    
    if (artistNameElement) {
        artistNameElement.textContent = artistName;
        artistNameElement.removeAttribute('data-i18n'); // 移除国际化标记，使用实际艺术家名
    }
    
    if (trackImageElement) trackImageElement.src = imageSrc;
} 

/**
 * 更新用户信息
 */
function updateUserInfo() {
    const userButtons = document.querySelectorAll('.user-menu');
    const premiumEl = document.querySelectorAll('.premium-item');
    
    // 检查当前用户是否已登录
    const currentUser = localStorage.getItem('shengpotian_current_user');
    
    if (currentUser) {
        try {
            const userData = JSON.parse(currentUser);
            
            // 更新用户名和头像显示
            userButtons.forEach(btn => {
                if (btn.querySelector('.user-dropdown')) {
                    // 已经初始化过，不需要再创建
                    return;
                }
                
                // 添加用户名和头像
                const userMenuHTML = `
                    <div class="user-avatar">
                        <img src="${userData.avatar || 'assets/images/avatars/default.png'}" alt="${userData.username}">
                        ${userData.isPremium ? '<span class="user-premium-badge"><i class="fas fa-star"></i></span>' : ''}
                    </div>
                    <span class="user-name">${userData.username}</span>
                `;
                btn.innerHTML = userMenuHTML;
            });
            
            // 更新菜单项，将"升级到Premium"替换为"管理订阅"（如果是会员）
            if (userData.isPremium) {
                premiumEl.forEach(item => {
                    item.innerHTML = '<i class="fas fa-star"></i> 管理订阅';
                    item.href = 'profile.html?tab=subscription';
                });
            }
        } catch (error) {
            console.error('解析用户数据失败:', error);
        }
    }
    
    // 加载上次的音频播放状态
    loadAudioPlaybackState();
}

// 加载音频播放状态
function loadAudioPlaybackState() {
    const savedState = localStorage.getItem('audioPlaybackState');
    if (savedState && window.globalAudioPlayer) {
        try {
            const state = JSON.parse(savedState);
            if (state.src && state.src !== window.globalAudioPlayer.src) {
                window.globalAudioPlayer.src = state.src;
                window.globalAudioPlayer.currentTime = state.currentTime || 0;
                
                // 如果之前是播放状态，尝试恢复播放
                // 但由于浏览器自动播放限制，可能需要用户交互
                if (state.isPlaying) {
                    const playPromise = window.globalAudioPlayer.play();
                    if (playPromise) {
                        playPromise.catch(e => {
                            console.log('需要用户交互才能恢复播放:', e);
                        });
                    }
                }
            }
        } catch (e) {
            console.error('恢复音频状态失败:', e);
        }
    }
}

// 应用全局样式调整
function applyStyles() {
    const styleElement = document.createElement('style');
    styleElement.textContent = `
        /* 歌曲名称链接样式 */
        .track-name a {
            color: inherit;
            text-decoration: none;
            transition: color 0.2s ease;
        }
        
        .track-name a:hover {
            color: #1DB954;
            text-decoration: underline;
        }
    `;
    document.head.appendChild(styleElement);
}

// 显示用户信息或登录/注册按钮
function updateUserUI() {
    // 实现用户信息显示逻辑
}

// 初始化语言切换
function initLanguageSelector() {
    // 实现语言切换逻辑
}

// 初始化顶部栏滚动隐藏
function initTopBarScrollHandling() {
    // 实现顶部栏滚动隐藏逻辑
}

// 初始化公共播放器，确保在页面间切换时音乐不会停止
function initPlayer() {
    // 如果全局播放器实例不存在，创建一个
    if (!window.globalAudioPlayer) {
        window.globalAudioPlayer = new Audio();
        window.globalAudioPlayer.volume = 0.7;
        console.log('创建全局音频播放器实例');
    }
    
    // 如果播放器控件存在，初始化它们
    const playButton = document.querySelector('.play-btn');
    if (playButton) {
        playButton.addEventListener('click', function() {
            if (window.globalAudioPlayer.paused) {
                window.globalAudioPlayer.play();
                this.innerHTML = '<i class="fas fa-pause"></i>';
            } else {
                window.globalAudioPlayer.pause();
                this.innerHTML = '<i class="fas fa-play"></i>';
            }
        });
    }
    
    // 在unload事件中保存当前播放状态
    window.addEventListener('beforeunload', function() {
        if (window.globalAudioPlayer) {
            localStorage.setItem('audioPlayerStatus', JSON.stringify({
                src: window.globalAudioPlayer.src,
                currentTime: window.globalAudioPlayer.currentTime,
                isPlaying: !window.globalAudioPlayer.paused
            }));
        }
    });
}

// 初始化主题
function initTheme() {
    // ... 已有代码 ...
}

// 初始化用户下拉菜单
function initUserDropdown() {
    // ... 已有代码 ...
}

// 登录状态处理
function checkLoginStatus() {
    // ... 已有代码 ...
}

// 保存音频播放状态
function saveAudioState() {
    if (window.globalAudioPlayer) {
        const state = {
            src: window.globalAudioPlayer.src,
            currentTime: window.globalAudioPlayer.currentTime,
            isPlaying: !window.globalAudioPlayer.paused && !window.globalAudioPlayer.ended
        };
        localStorage.setItem('audioPlaybackState', JSON.stringify(state));
    }
}

// 初始化公共功能
function initCommonFeatures() {
    // 初始化专辑封面点击事件
    initPlayerCoverClick();
    
    // 初始化底部播放器状态同步
    initPlayerStateSync();
}

// 初始化底部播放器的专辑封面点击事件
function initPlayerCoverClick() {
    const albumCover = document.querySelector('.player-bar .track-image');
    
    if (albumCover) {
        // 添加鼠标悬停样式
        albumCover.style.cursor = 'pointer';
        albumCover.title = '点击查看歌词页面';
        
        // 添加点击事件
        albumCover.addEventListener('click', function() {
            // 检查是否在播放器页面
            const isPlayerPage = window.location.pathname.includes('player.html');
            
            if (isPlayerPage) {
                // 如果在播放器页面，返回上一页
                console.log('返回上一页');
                window.history.back();
            } else {
                // 否则，跳转到播放器页面
                console.log('跳转到播放器页面');
                
                // 获取当前播放歌曲信息
                const trackName = document.querySelector('.track-name').textContent;
                const artistAlbum = document.querySelector('.artist-name').textContent;
                const coverSrc = document.querySelector('.track-image img').src;
                
                // 构建URL参数
                let params = new URLSearchParams();
                params.append('name', trackName);
                
                // 提取艺术家名称
                let artist = artistAlbum;
                if (artistAlbum.includes('-')) {
                    artist = artistAlbum.split('-')[0].trim();
                }
                
                params.append('artist', artist);
                params.append('type', 'track');
                
                // 如果存在音频播放器，添加当前播放时间
                if (window.audioPlayer) {
                    params.append('time', window.audioPlayer.currentTime);
                }
                
                // 添加封面图片参数
                if (coverSrc) {
                    // 从完整URL中提取相对路径
                    const imagePath = coverSrc.split('/').slice(-2).join('/');
                    params.append('image', imagePath);
                }
                
                // 跳转到播放器页面
                window.location.href = `player.html?${params.toString()}`;
            }
        });
    }
}

// 初始化底部播放器状态同步，确保在所有页面保持一致
function initPlayerStateSync() {
    // 检查是否存在底部播放器
    if (!document.querySelector('.player-bar')) return;
    
    // 创建音频对象（如果尚未创建）
    if (!window.audioPlayer) {
        window.audioPlayer = new Audio('assets/music/qingtian.mp3');
        
        // 加载上一次的音量设置
        const savedVolume = localStorage.getItem('currentVolume');
        if (savedVolume && !isNaN(parseFloat(savedVolume))) {
            window.audioPlayer.volume = parseFloat(savedVolume);
        } else {
            window.audioPlayer.volume = 0.7; // 默认音量
        }
        
        // 加载静音状态
        const wasMuted = localStorage.getItem('isMuted');
        if (wasMuted === 'true') {
            window.audioPlayer.muted = true;
        }
    }
    
    // 加载音频播放时间
    const savedTime = localStorage.getItem('currentPlayTime');
    if (savedTime && !isNaN(parseFloat(savedTime))) {
        window.audioPlayer.currentTime = parseFloat(savedTime);
    }
    
    // 监听播放进度更新
    window.audioPlayer.addEventListener('timeupdate', function() {
        updatePlayerProgress();
    });
    
    // 恢复播放按钮状态
    const wasPlaying = localStorage.getItem('wasPlaying') === 'true';
    updatePlayButtonUI(wasPlaying);
    
    // 初始化播放器控件
    initPlayerControls();
    
    // 更新音量UI
    updatePlayerVolumeUI();
    
    // 初始化UI状态
    updatePlayerInfoUI();
    
    // 确保进度条初始状态正确
    updatePlayerProgress();
}

// 更新播放进度
function updatePlayerProgress() {
    if (!window.audioPlayer) return;
    
    // 确保时间为0时进度条也是0
    let ratio = 0;
    if (window.audioPlayer.duration && window.audioPlayer.duration > 0) {
        ratio = window.audioPlayer.currentTime / window.audioPlayer.duration;
    }
    
    // 更新进度条
    const progress = document.querySelector('.player-bar .progress');
    const progressHandle = document.querySelector('.player-bar .progress-handle');
    
    if (progress) progress.style.width = `${ratio * 100}%`;
    if (progressHandle) progressHandle.style.left = `${ratio * 100}%`;
    
    // 更新时间显示
    const currentTime = document.querySelector('.player-bar .current-time');
    if (currentTime) {
        currentTime.textContent = formatTime(window.audioPlayer.currentTime);
    }
}

// 格式化时间
function formatTime(seconds) {
    if (isNaN(seconds)) return "0:00";
    const mins = Math.floor(seconds / 60);
    const secs = Math.floor(seconds % 60);
    return `${mins}:${secs < 10 ? '0' + secs : secs}`;
}

// 更新播放按钮UI
function updatePlayButtonUI(isPlaying) {
    const playBtn = document.querySelector('.player-bar .play-btn');
    if (!playBtn) return;
    
    if (isPlaying) {
        playBtn.innerHTML = '<i class="fas fa-pause"></i>';
    } else {
        playBtn.innerHTML = '<i class="fas fa-play"></i>';
    }
}

// 更新音量UI
function updatePlayerVolumeUI() {
    const volumeLevel = document.querySelector('.player-bar .volume-level');
    const volumeHandle = document.querySelector('.player-bar .volume-handle');
    const volumeBtn = document.querySelector('.player-bar .volume-control .option-btn i');
    
    if (!volumeLevel || !volumeHandle || !volumeBtn || !window.audioPlayer) return;
    
    const volume = window.audioPlayer.muted ? 0 : window.audioPlayer.volume;
    const percent = volume * 100;
    
    volumeLevel.style.width = `${percent}%`;
    volumeHandle.style.left = `${percent}%`;
    
    if (volume === 0 || window.audioPlayer.muted) {
        volumeBtn.className = 'fas fa-volume-mute';
    } else if (volume < 0.5) {
        volumeBtn.className = 'fas fa-volume-down';
    } else {
        volumeBtn.className = 'fas fa-volume-up';
    }
}

// 初始化播放器控件
function initPlayerControls() {
    // 播放/暂停按钮
    const playBtn = document.querySelector('.player-bar .play-btn');
    if (playBtn) {
        playBtn.addEventListener('click', function() {
            togglePlayback();
        });
    }
    
    // 音量按钮
    const volumeBtn = document.querySelector('.player-bar .volume-control .option-btn');
    if (volumeBtn) {
        volumeBtn.addEventListener('click', function() {
            toggleMute();
        });
    }
    
    // 音量条
    const volumeBar = document.querySelector('.player-bar .volume-bar');
    if (volumeBar) {
        volumeBar.addEventListener('click', function(e) {
            const rect = this.getBoundingClientRect();
            const clickPosition = e.clientX - rect.left;
            const newVolume = Math.max(0, Math.min(1, clickPosition / rect.width));
            
            if (window.audioPlayer) {
                window.audioPlayer.volume = newVolume;
                window.audioPlayer.muted = (newVolume === 0);
                updatePlayerVolumeUI();
                
                // 保存到localStorage
                localStorage.setItem('currentVolume', newVolume.toString());
                localStorage.setItem('isMuted', (newVolume === 0).toString());
            }
        });
    }
    
    // 进度条
    const progressBar = document.querySelector('.player-bar .progress-bar');
    if (progressBar && window.audioPlayer) {
        progressBar.addEventListener('click', function(e) {
            const rect = this.getBoundingClientRect();
            const clickPosition = e.clientX - rect.left;
            const ratio = clickPosition / rect.width;
            
            if (window.audioPlayer.duration) {
                const newTime = ratio * window.audioPlayer.duration;
                window.audioPlayer.currentTime = newTime;
                
                // 保存到localStorage
                localStorage.setItem('currentPlayTime', newTime.toString());
                
                // 更新UI
                updatePlayerProgress();
            }
        });
    }
}

// 切换播放/暂停状态
function togglePlayback() {
    if (!window.audioPlayer) return;
    
    if (window.audioPlayer.paused) {
        // 开始播放
        window.audioPlayer.play().catch(e => {
            console.log("播放失败，需要用户交互:", e);
        });
        updatePlayButtonUI(true);
        localStorage.setItem('wasPlaying', 'true');
    } else {
        // 暂停播放
        window.audioPlayer.pause();
        updatePlayButtonUI(false);
        localStorage.setItem('wasPlaying', 'false');
    }
}

// 切换静音状态
function toggleMute() {
    if (!window.audioPlayer) return;
    
    const previousVolume = parseFloat(localStorage.getItem('currentVolume') || '0.7');
    
    if (window.audioPlayer.muted || window.audioPlayer.volume === 0) {
        // 恢复音量
        window.audioPlayer.muted = false;
        window.audioPlayer.volume = previousVolume > 0 ? previousVolume : 0.7;
        localStorage.setItem('isMuted', 'false');
    } else {
        // 静音
        window.audioPlayer.muted = true;
        localStorage.setItem('isMuted', 'true');
    }
    
    updatePlayerVolumeUI();
}

// 更新播放器显示信息
function updatePlayerInfoUI() {
    // 获取保存的曲目信息
    const savedTrackJSON = localStorage.getItem('currentTrack');
    if (savedTrackJSON) {
        try {
            const track = JSON.parse(savedTrackJSON);
            const trackName = document.querySelector('.player-bar .track-name');
            const artistName = document.querySelector('.player-bar .artist-name');
            const coverImg = document.querySelector('.player-bar .track-image img');
            
            if (trackName) trackName.textContent = track.title || '未知歌曲';
            if (artistName) artistName.textContent = `${track.artist || '未知艺术家'} - ${track.album || ''}`;
            if (coverImg && track.cover) coverImg.src = track.cover;
        } catch (e) {
            console.error('解析保存的曲目信息失败:', e);
        }
    }
}